package com.aio.news.net;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.aio.news.utils.AppConstance;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

public class HttpUtils {

	public static CallbackHandler mHandler;

	public static enum Method {
		POST, GET
	}

	private static void HttpGet(List<NameValuePair> params, String method,
			HttpInterface listener) {
		HttpClient client = new DefaultHttpClient();
		StringBuilder builder = new StringBuilder();
		builder.append(AppConstance.BASE_URL);
		builder.append(method);
		if (params != null && params.size() > 0) {
			for (NameValuePair param : params) {
				builder.append("/");
				builder.append(param.getValue());
			}
		}

		Log.e("jql", builder.toString());

		HttpGet httpGet = new HttpGet(builder.toString());
		try {
			HttpResponse response = client.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entry = response.getEntity();
				String content = EntityUtils.toString(entry, HTTP.UTF_8);
				Message msg = new Message();
				Object[] objects = new Object[2];
				objects[0] = content;
				objects[1] = listener;
				msg.obj = objects;
				msg.what = 1;
				mHandler.sendMessage(msg);
			} else {
				HttpEntity entry = response.getEntity();
				String content = EntityUtils.toString(entry, HTTP.UTF_8);
				Message msg = new Message();
				Object[] objects = new Object[2];
				objects[0] = content;
				objects[1] = listener;
				msg.obj = objects;
				msg.what = 0;
				mHandler.sendMessage(msg);
			}
		} catch (Exception e) {
		}
	}

	public static void HttpPostRequest(List<NameValuePair> params,
			String method, HttpInterface listener) {
		doPostWithFile(params, method, null, null, listener);
	}

	public static void doPostWithFile(List<NameValuePair> params,
			String method, String fileKey, byte[] b, HttpInterface listener) {
		HttpClient client = new DefaultHttpClient();
		StringBuilder builder = new StringBuilder();
		builder.append(AppConstance.BASE_URL);
		builder.append(method);
		Log.e("jql", "post: "+builder.toString());
		HttpPost post = new HttpPost(builder.toString());
//		post.addHeader("Content-Type","application/json");
		try{
			if(TextUtils.isEmpty(fileKey) || b == null){
				post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			}else{
				HttpEntity entity = new ByteArrayEntity(b);
//				post.setEntity(fileEntity(params, fileKey, b));
				post.setEntity(entity);
			}
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entry = response.getEntity();
				String content = EntityUtils.toString(entry, HTTP.UTF_8);
				Message msg = new Message();
				Object[] objects = new Object[2];
				objects[0] = content;
				objects[1] = listener;
				msg.obj = objects;
				msg.what = 1;
				mHandler.sendMessage(msg);
			} else {
				HttpEntity entry = response.getEntity();
				String content = EntityUtils.toString(entry, HTTP.UTF_8);
				Message msg = new Message();
				Object[] objects = new Object[2];
				objects[0] = content;
				objects[1] = listener;
				msg.obj = objects;
				msg.what = 0;
				mHandler.sendMessage(msg);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static HttpEntity fileEntity(List<NameValuePair> params,String filekey,byte[] b){
		MultipartEntity entry = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
		for(NameValuePair param : params){
			try {
				entry.addPart(param.getName(),new StringBody(param.getValue()));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		if(b != null){
			ByteArrayBody body = new ByteArrayBody(b, filekey);
			entry.addPart(filekey, body);
		}
		return entry;
	}

	public static void doAsyncGet(final List<NameValuePair> params,
			final String method, final HttpInterface listener) {
		if (mHandler == null)
			mHandler = new CallbackHandler();
		new Thread() {

			@Override
			public void run() {
				HttpGet(params, method, listener);
			}

		}.start();
	}

	public static void doAsyncPost(final List<NameValuePair> params,
			final String method, final HttpInterface listener) {
		if (mHandler == null)
			mHandler = new CallbackHandler();
		new Thread() {

			@Override
			public void run() {
				HttpPostRequest(params, method, listener);
			}

		}.start();
	}
	
	public static void doAsyncPost(final List<NameValuePair> params,
			final String method,final String fileKey,final byte[] b, final HttpInterface listener) {
		if (mHandler == null)
			mHandler = new CallbackHandler();
		new Thread() {

			@Override
			public void run() {
				doPostWithFile(params, method, fileKey, b, listener);
			}

		}.start();
	}
	

	private static HttpParams params() {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setSoTimeout(params, 15 * 1000);
		// HttpProtocolParams.setUserAgent(params, "android dianping 1.0.0");
		return params;
	}

	public static class RequestState {
		public String requestUrl;
		public String response;
		public boolean isRequestServer = false;
		public boolean isBottom = false;
		public boolean isRefresh = false;
		public int page = 0;
		public int offset = 0;
		public String tid = "";

		public RequestState(String requestUrl) {
			this.requestUrl = requestUrl;
		}
	}

	public static class CallbackHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			Object[] obj = (Object[]) msg.obj;
			String content = obj[0].toString();
			HttpInterface listener = (HttpInterface) obj[1];
			if (msg.what == 1) {
				listener.success(content);
			} else {
				listener.failed(content);
			}
		}

	}
}
